//
//  TTWaitConfirmViewController.m
//  TaoTuo
//
//  Created by admin on 2019/9/29.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTWaitConfirmViewController.h"
#import "TTOrderViewCell.h"
#import "TTOrderModel.h"
#import "TTLookProgressViewController.h"

static NSString *cellID = @"wait_cell_id";

static NSMutableDictionary *needRefreshDic = nil;   // 是否要刷新

@interface TTWaitConfirmViewController ()<UITableViewDelegate, UITableViewDataSource, TTOrderViewCellDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) int page;
@property (nonatomic, assign) int status;   //订单状态

@end

@implementation TTWaitConfirmViewController

- (instancetype)initWithStatus:(int)status
{
    self = [super init];
    if (self) {
        
        self.status = status;
        // 初始值
        if (needRefreshDic == nil) {
            needRefreshDic = [NSMutableDictionary dictionary];
        }
        [needRefreshDic setObject:@(NO) forKey:[NSString stringWithFormat:@"%d", status]];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColorHex(#F5F5F5);
    
    @weakify(self)
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        self.page = 1;
        [self getNetworkDatas];
    }];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        @strongify(self)
        self.page++;
        [self getNetworkDatas];
    }];
    
    NSString *statusKey = [NSString stringWithFormat:@"%d", self.status];
    if (![needRefreshDic[statusKey] boolValue]) {
        [self.tableView.mj_header beginRefreshing];
    }
    
    // 设置页面刷新状态
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setPageRefreshStatus:) name:@"setPageRefreshStatusNotify" object:nil];
    
    //替换裸石成功刷新页面的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(replaceLuoshiSuccessRefreshDatas) name:@"replaceLuoshiSuccessNotify_key" object:nil];
    
}

// 设置页面刷新状态
- (void)setPageRefreshStatus:(NSNotification *)notify
{
    NSString *key = [NSString stringWithFormat:@"%d", self.status];
    needRefreshDic[key] = @(YES);
    
}

//替换裸石成功刷新页面的通知
- (void)replaceLuoshiSuccessRefreshDatas
{
    self.page = 1;
    [self getNetworkDatas];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTOrderViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    cell.model = self.dataArray[indexPath.row];
    cell.delegate = self;
    cell.backgroundColor = UIColorHex(#F5F5F5);
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTOrderModel *model = self.dataArray[indexPath.row];
    return model.H;
}

#pragma mark - TTOrderViewCellDelegate
// 取消订单
- (void)cancleButtonClickWithOrderViewCell:(TTOrderViewCell *)cell model:(TTOrderModel *)model
{
    @weakify(self)
    LLSystemAlertView *alertView = [LLSystemAlertView alertViewWithTitle:@"提示" message:@"确定取消此商品订单吗？" cancelTitle:@"取消" cancelBlock:nil confirmTitle:@"确定" confirmBlock:^BOOL{
        @strongify(self)
        [self cancelOrderWithOrderViewCell:cell model:model];
        return YES;
    }];
    [alertView showInView:nil animationDuration:0.3];
    
    
}

// 删除订单
- (void)deleteButtonClickWithOrderViewCell:(TTOrderViewCell *)cell model:(TTOrderModel *)model
{
    @weakify(self)
    LLSystemAlertView *alertView = [LLSystemAlertView alertViewWithTitle:@"提示" message:@"确定删除此商品吗？" cancelTitle:@"取消" cancelBlock:nil confirmTitle:@"确定" confirmBlock:^BOOL{
        @strongify(self)
        [self deleteShopWithOrderViewCell:cell model:model];
        return YES;
    }];
    [alertView showInView:nil animationDuration:0.3];
}

// 确定取消订单
- (void)cancelOrderWithOrderViewCell:(TTOrderViewCell *)cell model:(TTOrderModel *)model
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

    NSDictionary *dic = @{
        @"param.orderNo" : model.OrderNo,
        @"param.relationName" : [TTLoginSingle sharedSingle].loginModel.RealName
    };
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postUrlString:cancleOrder_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)

        if (self.status == 0) {
            // 全部订单页面，刷新页面
            self.page = 1;
            [self getNetworkDatas];
        } else {
            [self.dataArray removeObject:model];
            if (self.dataArray.count == 0) {
                [self.tableView reloadData];
            } else {
                [self.tableView deleteRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationFade];
            }
        }

        // 设置其他的需要刷新
        for (NSString *key in needRefreshDic.allKeys) {
            if (key.intValue != self.status) {
                needRefreshDic[key] = @(YES);
            }
        }

        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshPageCountNotify" object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"goodsCountChange_notifyKey" object:nil];

    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {

    } showLoadingInView:self.view];
}

- (void)deleteShopWithOrderViewCell:(TTOrderViewCell *)cell model:(TTOrderModel*)model
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    NSDictionary *dic = @{
        @"param.orderNo" : model.OrderNo,
        @"param.relationName" : [TTLoginSingle sharedSingle].loginModel.RealName
    };
    [[LLNetworkManagerTool sharedManager] postUrlString:deleteOrder_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self.dataArray removeObject:model];
        if (self.dataArray.count == 0) {
            [self.tableView reloadData];
        } else {
            [self.tableView deleteRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationFade];
        }
        
        // 设置其他的需要刷新
        for (NSString *key in needRefreshDic.allKeys) {
            if (key.intValue != self.status) {
                needRefreshDic[key] = @(YES);
            }
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshPageCountNotify" object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"goodsCountChange_notifyKey" object:nil];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}

// 查看进度
- (void)checkScheduleButtonClickWithOrderViewCell:(TTOrderViewCell *)cell model:(TTOrderModel *)model
{
    TTLookProgressViewController *progressVC = [[TTLookProgressViewController alloc] initWithOrderNum:model.OrderNo];
    [[LLRouteTool getCurrentNavigationController] pushViewController:progressVC animated:YES];
}

- (void)getNetworkDatas
{
    @weakify(self)
    [TTCommonNetData getOrderListWithOrderState:self.status page:self.page success:^(NSURLSessionDataTask * _Nonnull task, NSMutableArray * _Nonnull array) {
        @strongify(self)
        if (self.page == 1) {
            [self.dataArray removeAllObjects];
        }
        [self.dataArray addObjectsFromArray:array];
        
        [self.tableView.mj_header endRefreshing];
        if (array.count < 40) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
        
        [self.tableView reloadData];
        
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
    } showLoadingInView:self.view];
    
    
}


- (UIView *)listView
{
    return self.view;
}

- (void)listWillAppear
{
    NSString *statusKey = [NSString stringWithFormat:@"%d", self.status];
    if ([needRefreshDic[statusKey] boolValue]) {
        // 刷新
        [self.tableView.mj_header beginRefreshing];
        needRefreshDic[statusKey] = @(NO);
    }
    
}


- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.backgroundColor = UIColorHex(#F5F5F5);
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.emptyImageName = @"nodata";
        _tableView.emptyTitel = @"暂无数据";
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[TTOrderViewCell class] forCellReuseIdentifier:cellID];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(self.mas_topLayoutGuideTop);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideBottom);
        }];
    }
    return _tableView;
}



- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)dealloc
{
    NSLog(@"[< %@ >] --> 释放了", self.className);
    [needRefreshDic removeAllObjects];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
